﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;

using LEEAAttendanceControl.Web;
using LEEAAttendanceControl.Web.Services;

using LEEAAttendanceControl.AttendanceReference;

using System.ServiceModel;

using System.ServiceModel.DomainServices.Client;
using System.Windows.Browser;
using System.ComponentModel;
using System.Collections.ObjectModel;
using LEEAAttendanceControl.General;

namespace LEEAAttendanceControl.Views
{
    public partial class ShiftAssignments : Page
    {
        LEEAContext context = new LEEAContext();

        private CheckBox checkAllBox = null;

        ObservableCollection<int> employees = new ObservableCollection<int>();

        Dictionary<int, ObservableCollection<int>> days = new Dictionary<int, ObservableCollection<int>>();

        public ShiftAssignments()
        {
            InitializeComponent();

            ChangeEmployees();
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            App myApp = (App)Application.Current;

            myApp.ClearEvents();

            myApp.ChangeEmployeesEvent += ChangeEmployeesHandler;
        }

        public void ChangeEmployeesHandler(object sender, EventArgs e)
        {
            ChangeEmployees();
        }

        private void ReloadShiftsHandler(object sender, EventArgs e)
        {
            ShiftsDataSource.QueryParameters.Clear();

            Parameter comParameter = new Parameter();

            comParameter.ParameterName = "companyID";
            comParameter.Value = ((App)Application.Current).CompanyID.Value;

            ShiftsDataSource.QueryParameters.Add(comParameter);

            ShiftsDataSource.Load();
        }

        void ChangeEmployees()
        {
            if (checkAllBox != null && checkAllBox.IsChecked.Value)
            {
                checkAllBox.IsChecked = false;
            }

            EmployeesGrid.ItemsSource = null;

            context.EmployeeSummaries.Clear();

            int companyID = ((App)Application.Current).CompanyID ?? 0;

            int departmentID = ((App)Application.Current).DepartmentID ?? 0;

            int employeeID = ((App)Application.Current).EmployeeId;

            context.Load(context.GetEmployeeSummariesForShiftsQuery(companyID, departmentID, employeeID)
                , OnEmployeesLoadCompleted, null);
        }

        private void OnEmployeesLoadCompleted(LoadOperation load)
        {
            EmployeesGrid.ItemsSource = load.Entities;

            ReloadShiftsHandler(null, new EventArgs());
        }

        private void DomainDataSource_LoadingData(object sender, LoadingDataEventArgs e)
        {
            e.LoadBehavior = LoadBehavior.RefreshCurrent;
        }
        
        private void SelectAllCheckBox_Click(object sender, RoutedEventArgs e)
        {
            employees.Clear();

            CheckBox selector = sender as CheckBox;

            if (checkAllBox == null)
            {
                checkAllBox = selector;
            }

            foreach (var item in EmployeesGrid.ItemsSource)
            {
                EmployeeSummary emp = item as EmployeeSummary;

                emp.IsChecked = selector.IsChecked.Value;
                
                if (selector.IsChecked.Value)
                {
                    employees.Add(emp.EmployeeID);
                } 
            }
        }

        private void EmployeeCheck_Click(object sender, RoutedEventArgs e)
        {
            EmployeeSummary emp = EmployeesGrid.SelectedItem as EmployeeSummary;

            if (emp.IsChecked)
            {
                employees.Add(emp.EmployeeID);
            }
            else
            {
                employees.Remove(emp.EmployeeID);

                if (checkAllBox != null && checkAllBox.IsChecked.Value)
                {
                    checkAllBox.IsChecked = false;
                }
            }
        }

        private void SaturdayBox_Click(object sender, RoutedEventArgs e)
        {
            DeselectOthers(sender, 1);
        }

        private void SundayBox_Click(object sender, RoutedEventArgs e)
        {
            DeselectOthers(sender, 2);
        }

        private void MondayBox_Click(object sender, RoutedEventArgs e)
        {
            DeselectOthers(sender, 3);
        }

        private void TuesdayBox_Click(object sender, RoutedEventArgs e)
        {
            DeselectOthers(sender, 4);
        }

        private void WednesdayBox_Click(object sender, RoutedEventArgs e)
        {
            DeselectOthers(sender, 5);
        }

        private void ThursdayBox_Click(object sender, RoutedEventArgs e)
        {
            DeselectOthers(sender, 6);
        }

        private void FridayBox_Click(object sender, RoutedEventArgs e)
        {
            DeselectOthers(sender, 7);
        }

        private void DeselectOthers(object sender, int columnIndex)
        {
            CheckBox selected = sender as CheckBox;

            if (selected.IsChecked.Value)
            {
                foreach (var item in ShiftsGrid.ItemsSource)
                {
                    if (ShiftsGrid.SelectedItem != item)
                    {
                        Grid grid = ShiftsGrid.Columns[columnIndex].GetCellContent(item) as Grid;

                        CheckBox satBox = grid.Children.FirstOrDefault() as CheckBox;

                        satBox.IsChecked = false;
                    }
                }
            }
        }

        private void ApplyButton_Click(object sender, RoutedEventArgs e)
        {
            if (FromPicker.Text == string.Empty || ToPicker.Text == string.Empty)
            {
                MessageDisplay message = new MessageDisplay("Please Select Dates", "Error", "Error");

                message.Closed += (s, ee) =>
                    {
                        return;
                    };

                message.Show();
            }
            foreach (var item in ShiftsGrid.ItemsSource)
            {
                Shift sh = item as Shift;

                for (int i = 1; i < 8; i++)
                {
                    Grid grid = ShiftsGrid.Columns[i].GetCellContent(item) as Grid;

                    CheckBox dayBox = grid.Children.FirstOrDefault() as CheckBox;

                    if (dayBox.IsChecked.Value)
                    {
                        if (!days.Keys.Contains(sh.ID))
                        {
                            days[sh.ID] = new ObservableCollection<int>();
                        }

                        days[sh.ID].Add(i);
                    }
                }
            }

            AttendanceServiceClient proxy = General.General.GetProxy();

            proxy.WriteUserSelectionCompleted += OnWriteSelectionCompleted;

            proxy.WriteUserSelectionAsync(employees, days, FromPicker.SelectedDate.Value
                , ToPicker.SelectedDate.Value, "New");
        }

        private void OnWriteSelectionCompleted(object sender, AsyncCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageDisplay message = new MessageDisplay(ApplicationStrings.GeneralError
                    , ApplicationStrings.GeneralError, "Error");

                message.Show();
            }
            else
            {
                NavigationService.Navigate(new Uri("/Views/EmployeesShifts.xaml", UriKind.Relative));
            }
        }
    }
}
